package org.baixin.action.permission;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.json.annotations.JSON;
import org.baixin.action.BaseAction;
import org.baixin.core.PropertyFilter;
import org.baixin.entity.Organization;
import org.baixin.entity.Resource;
import org.baixin.entity.Role;
import org.baixin.entity.User;
import org.baixin.exception.AppException;
import org.baixin.manager.OrganizationManager;
import org.baixin.manager.RoleManager;
import org.baixin.manager.UserManager;
import org.baixin.utils.encode.EncodeUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 * 用户控制器
 * 
 * @author slaton.wu@gmail.com
 * @version 1.0
 * @created 2011-6-11 下午07:37:56
 */
@ParentPackage("json-default")
@Namespace("/user")
@Results({
		@Result(name = BaseAction.LOGIN, location = "user/login.jsp"),
		@Result(name = BaseAction.INPUT, location = "/user/login.htm", type = "redirect"),
		@Result(name = BaseAction.SUCCESS, location = "/home/main.htm", type = "redirect"),
		@Result(name = "delete", location = "/user/list.htm"),
		@Result(type="json",name="verify"),
		@Result(name = "list", location = "/WEB-INF/pages/user/list.jsp" ),
		@Result(name = "add", location = "/WEB-INF/pages/user/input.jsp" )
})
public class UserAction extends BaseAction<User, UserManager> {

	private User user;
	
	private RoleManager roleManager;
	
	private List<Long> checkedRoleIds;
	
	private List<Long> checkedOrgIds;
	
	private OrganizationManager organizationManager;
	
	@Action("/login")
	public String login() throws AppException {

		return LOGIN;
	}

	@Action("/loginUser")
	public String loginUser() throws AppException {

		if (user!=null) {
			user.setPawd(EncodeUtils.md5(user.getPawd()));
			user = entityManager.login(user);
		}
		if (user == null) {
			request.getSession().setAttribute("error", "*用户名或密码不正确！");
			return INPUT;
		}
		if (user.getStatus()!=null&&"1".equals(user.getStatus())) {
			request.getSession().setAttribute("error", "*您的用户名被限制登陆！");
			return INPUT;
		}
		request.getSession().removeAttribute("error");
		request.getSession().setAttribute("login_user", user);
		List<Resource> list = getResource();
		request.getSession().setAttribute("res", list);
		return SUCCESS;
	}

	/**
	 * @return
	 * @throws AppException
	 * @see org.baixin.action.BaseAction#list()
	 */
	@Action("/user/list")
	@Override
	public String list() throws AppException {
		
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		page = entityManager.search(page,filters);
		return LIST;
	}

	/**
	 * @return
	 * @throws AppAppException
	 * @see org.baixin.action.BaseAction#input()
	 */
	@Action("/user/input")
	@Override
	public String input() throws AppException {
		if (user!=null) {
			checkedRoleIds = user.getRoleIds();
			checkedOrgIds = user.getOrgIds();
		}
		return "add";
	}
	@Action("/user/loginOut")
	public String loginout() throws AppException{
		request.getSession().removeAttribute("login_user");
		return INPUT;
	}

	/**
	 * @return
	 * @throws AppException
	 * @see org.baixin.action.BaseAction#save()
	 */
	@Action("/user/save")
	@Override
	public String save() throws AppException {
		
		if (user!=null&&user.getLoginName()!=null) {
			List<User> us = entityManager.getAll("loginName", user.getLoginName());
			String path = request.getContextPath();
			String ctx = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
			if (us!=null&&us.size()>0) {
				request.setAttribute("user", user);
				request.setAttribute("verifyName", "<img src='"+ctx+"resources/images/exist.png'/><font style='font-size:12px;color:red;'>用户名已存,请换一个再试!</font>");
				return "add";
			}
			us = entityManager.getAll("email", user.getEmail());
			if (us!=null&&us.size()>0) {
				request.setAttribute("user", user);
				request.setAttribute("verifyEmail", "<img src='"+ctx+"resources/images/exist.png'/><font style='font-size:12px;color:red;'>邮箱名已存,请换一个再试!</font>");
				return "add";
			}
			
		}
		if (user!=null&&user.getId()==null) {
			user.setPawd(EncodeUtils.md5(user.getPawd()));
			user = entityManager.add(user);
		}
		return SUCCESS;
	}

	/**
	 * @return
	 * @throws AppException
	 * @see org.baixin.action.BaseAction#delete()
	 */
	@Action("/user/delete")
	@Override
	public String delete() throws AppException {
		if (ids!=null&&!"".equals(StringUtils.trim(ids))) {
			StringTokenizer st = new StringTokenizer(ids, ",");
			while (st.hasMoreElements()) {
				String id = (String) st.nextElement();
				if (id!=null&&!"".equals(StringUtils.trim(id))) {
					entityManager.delete(Long.parseLong(id));
				}
			}
		}
		this.operate = "1";
		return "delete";
	}
	
	/**
	 * input页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		
		return (List<Role>) roleManager.getAll();
	}
	/**
	 * input页面显示所有角色列表.
	 */
	public List<Organization> getAllOrgList() {
		
		return (List<Organization>) organizationManager.getAll();
	}

	/**
	 * @param entityManager
	 * @see org.baixin.action.BaseAction#setEntityManager(org.baixin.manager.BaseManager)
	 */
	@Override
	@Autowired
	public void setEntityManager(UserManager userManager) {
		this.entityManager = userManager;
	}

	/**
	 * 设置 roleManager 的值
	 * @param roleManager
	 */
	@Autowired
	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}
	
	/**
	 * 描述
	 * 
	 * @return
	 */
	private List<Resource> getResource() {
		List<Resource> res = new ArrayList<Resource>();
		if (user!=null) {
			List<Role> roles = user.getRoles();
			if (roles!=null&&roles.size()>0) {
				for (Role role : roles) {
					List<Resource> reses = role.getReses();
					for (Resource resource : reses) {
						if (!res.contains(resource)) {
							res.add(resource);
						}
					}
				}
			}
		}
		return res;
	}

	/**
	 * 返回 user 的值
	 * @return user
	 */
	
	public User getUser() {
		return user;
	}

	/**
	 * 设置 user 的值
	 * @param user
	 */
	
	public void setUser(User user) {
		this.user = user;
	}
	
	/**
	 * 返回 checkedRoleIds 的值
	 * @return checkedRoleIds
	 */
	
	public List<Long> getCheckedRoleIds() {
		return checkedRoleIds;
	}

	/**
	 * 返回 checkedOrgIds 的值
	 * @return checkedOrgIds
	 */
	
	public List<Long> getCheckedOrgIds() {
		return checkedOrgIds;
	}
	

	/**
	 * 设置 checkedRoleIds 的值
	 * @param checkedRoleIds
	 */
	
	public void setCheckedRoleIds(List<Long> checkedRoleIds) {
		this.checkedRoleIds = checkedRoleIds;
	}

	/**
	 * 设置 checkedOrgIds 的值
	 * @param checkedOrgIds
	 */
	
	public void setCheckedOrgIds(List<Long> checkedOrgIds) {
		this.checkedOrgIds = checkedOrgIds;
	}

	/**
	 * 设置 organizationManager 的值
	 * @param organizationManager
	 */
	@Autowired
	public void setOrganizationManager(OrganizationManager organizationManager) {
		this.organizationManager = organizationManager;
	}

}
